﻿using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Reflection;
using System.Text;
using System.Web;
using System.Web.Script.Serialization;
using bmapi.Controllers;
using Newtonsoft.Json;

namespace bmapi.HelperClass
{
    public class AssistFun
    {
        /// <summary>
        /// 对象转json
        /// </summary> 
        /// <param name="obj"></param>
        /// <returns></returns>
        public static HttpResponseMessage toJson(Object obj)
        {
            String str;
            if (obj is String || obj is Char)
            {
                str = obj.ToString();
            }
            else
            {
                JavaScriptSerializer serializer = new JavaScriptSerializer();
                str = serializer.Serialize(obj);
            }
            HttpResponseMessage result = new HttpResponseMessage { Content = new StringContent(str, Encoding.GetEncoding("UTF-8"), "application/json") };
            return result;
        }

        /// <summary>
        /// 将datable转换为List<T>
        /// </summary>
        /// <typeparam name="T">返回的数据类型</typeparam>
        /// <param name="dt">datable</param>
        /// <returns>List<T></returns>
        public static List<T> DataTableToList<T>(DataTable dt) where T : class, new()
        {
            //创建一个属性的列表    
            List<PropertyInfo> prlist = new List<PropertyInfo>();
            //获取TResult的类型实例  反射的入口    
            Type t = typeof(T);
            //获得TResult 的所有的Public 属性 并找出TResult属性和DataTable的列名称相同的属性(PropertyInfo) 并加入到属性列表     
            Array.ForEach<PropertyInfo>(t.GetProperties(), p => { if (dt.Columns.IndexOf(p.Name) != -1) prlist.Add(p); });
            //创建返回的集合    
            List<T> oblist = new List<T>();
            foreach (DataRow row in dt.Rows)
            {
                
                //创建TResult的实例    
                T ob = new T();
                //找到对应的数据  并赋值    
                prlist.ForEach(p => {
                    if (row[p.Name] != DBNull.Value)
                        p.SetValue(ob, row[p.Name], null);
                });


                //放入到返回的集合中    
                oblist.Add(ob);
            }
            return oblist;
        }

        /// <summary>
        /// DataRow转Object
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="dr"></param>
        /// <returns></returns>
        public static T DataRowToObject<T>(DataRow dr)
        {

            if (dr == null)
            {
                return default(T);
            }

            T model = (T)Activator.CreateInstance(typeof(T));
            PropertyInfo[] propertyInfos = model.GetType().GetProperties();

            for (int i = 0; i < dr.Table.Columns.Count; i++)
            {
                //if (dr[propertyInfos[i].Name] is DBNull)
                //{
                //    propertyInfos[i].SetValue(model, null, null);
                //    continue;
                //}
                if (propertyInfos[i] != null && dr[i] != DBNull.Value)
                    propertyInfos[i].SetValue(model, dr[propertyInfos[i].Name], null);
                else continue;
            }

            //for (int i = 0; i < dr.Table.Columns.Count; i++)
            //{
            //    PropertyInfo propertyInfo = model.GetType().GetProperty(dr.Table.Columns[i].ColumnName);

            //    if (propertyInfo != null && dr[i] != DBNull.Value)
            //        propertyInfo.SetValue(model, dr[i], null);
            //    else continue;
            //}
            return model;
        }


        public static HttpResponseMessage DataTableToJson(DataTable dt)
        {
            string str = string.Empty;
            str = JsonConvert.SerializeObject(dt);
            HttpResponseMessage result = new HttpResponseMessage { Content = new StringContent(str, Encoding.GetEncoding("UTF-8"), "application/json") };
            return result;
        }

        public class JsonToObject
        {

            public static Object JsonTObj(String json, Type t)
            {
                try
                {
                    System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(t);
                    using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(json)))
                    {

                        return serializer.ReadObject(ms);
                    }
                }
                catch
                {
                    return null;
                }
            }

        }

        //比较两个值的大小
        public static int GetMax(int x, int y)
        {
            if (x > y)
                return x;
            else
                return y;
        }

        /// <summary>
        /// 将两个列不同的DataTable合并成一个新的DataTable
        /// </summary>
        /// <param name="dt1">表1</param>
        /// <param name="dt2">表2</param>
        /// <param name="DTName">合并后新的表名</param>
        /// <returns></returns>
        public static DataTable UniteDataTable(DataTable dt1, DataTable dt2, string DTName)
        {
            DataTable dt3 = dt1.Clone();
            for (int i = 0; i < dt2.Columns.Count; i++)
            {
                dt3.Columns.Add(dt2.Columns[i].ColumnName);
            }
            object[] obj = new object[dt3.Columns.Count];

            for (int i = 0; i < dt1.Rows.Count; i++)
            {
                dt1.Rows[i].ItemArray.CopyTo(obj, 0);
                dt3.Rows.Add(obj);
            }
            if (dt1.Rows.Count >= dt2.Rows.Count)
            {
                for (int i = 0; i < dt2.Rows.Count; i++)
                {
                    for (int j = 0; j < dt2.Columns.Count; j++)
                    {
                        dt3.Rows[i][j + dt1.Columns.Count] = dt2.Rows[i][j].ToString();
                    }
                }
            }
            else
            {
                DataRow dr3;
                for (int i = 0; i < dt2.Rows.Count - dt1.Rows.Count; i++)
                {
                    dr3 = dt3.NewRow();
                    dt3.Rows.Add(dr3);
                }
                for (int i = 0; i < dt2.Rows.Count; i++)
                {
                    for (int j = 0; j < dt2.Columns.Count; j++)
                    {
                        dt3.Rows[i][j + dt1.Columns.Count] = dt2.Rows[i][j].ToString();
                    }
                }
            }
            dt3.TableName = DTName; //设置DT的名字
            return dt3;
        }
        public static DataTable UniteDataTables(DataTable dt1, DataTable dt2)
        {
            DataTable dt3 = dt1.Clone();
            dt3.Rows.Clear();
            object[] obj = new object[dt3.Columns.Count];
            for (int i = 0; i < dt1.Rows.Count; i++)
            {
                dt1.Rows[i].ItemArray.CopyTo(obj, 0);
                dt3.Rows.Add(obj);
            }
            for (int i = 0; i < dt2.Rows.Count; i++)
            {
                dt2.Rows[i].ItemArray.CopyTo(obj, 0);
                dt3.Rows.Add(obj);
            }
            return dt3;
        }
    }
}